package com.mycc.lease.common.utils;

import com.mycc.lease.common.exception.LeaseException;
import com.mycc.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;

import java.util.Date;

public class JwUtil {
    private static long tokenExpiration = 60 * 60 * 1000L*24;
    private static String myKey = "M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ6pYGVWWfDZw90a0lTpGYX1d4AQ6pYGVWWfDZw90a0lTpGYX1d4AQ";
    private static final SecretKey tokenSignKey = Keys.hmacShaKeyFor(myKey.getBytes());//    生成token
    public static String createToken(Long userId, String userName) {
            String jwt = Jwts.builder().
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                setSubject("LOGIN_USER").
                claim("userId", userId).
                claim("userName", userName).
                signWith(tokenSignKey, SignatureAlgorithm.HS256).
                compact();
        return jwt;

    }
//    校验token
    public static Claims parseToken(String token) {
        if (token == null){
            throw  new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParserBuilder jwtParserBuilder = Jwts.parser().setSigningKey(myKey);
            Jws<Claims> claimsJws = jwtParserBuilder.build().parseClaimsJws(token);
            Claims claims = claimsJws.getBody();

            return claims;
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }

    }

    public static void main(String[] args) {
        String generatedToken = createToken(1L, "admin");
        System.out.println(generatedToken);
   }
}
